package com.xcx.services.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcx.common.dto.req.DetectFaceReq;
import com.xcx.common.dto.resp.DetectFaceResp;
import com.xcx.common.enums.UserSexEnum;
import com.xcx.common.services.common.AiService;
import com.xcx.common.utils.CheckParamUtils;
import com.xcx.common.utils.ExceptionUtils;
import com.xcx.common.utils.HttpUtils;
import com.xcx.common.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AiServiceImpl implements AiService {


    /**
     * 面部识别
     * 文档：https://ai.qq.com/doc/detectface.shtml
     *
     * @param detectFaceReq
     * @return
     */
    @Override
    public DetectFaceResp detectFace(DetectFaceReq detectFaceReq) {
        log.info("detectFace req:{}", detectFaceReq.toString());
        DetectFaceResp baseResp = new DetectFaceResp();
        try {
            CheckParamUtils.validateReqGson(detectFaceReq);
            String url = "https://api.ai.qq.com/fcgi-bin/face/face_detectface";
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            parameterMap.put("app_id", detectFaceReq.getAppId());
            parameterMap.put("time_stamp", detectFaceReq.getTimeStamp());
            parameterMap.put("nonce_str", RandomUtil.getRandomString(30));
            parameterMap.put("sign", detectFaceReq.getSign());
            parameterMap.put("image", detectFaceReq.getImage());
            parameterMap.put("mode", 0);
            StringBuffer sb = HttpUtils.URLPost(url, parameterMap, 10 * 1000);
            JSONObject obj = (JSONObject) JSON.parseObject(sb.toString()).get("data");
            JSONArray array = (JSONArray) obj.get("face_list");
            JSONObject a = (JSONObject) array.get(0);
            Integer gender = (Integer) a.get("gender");

            baseResp.setUserSex(gender > 50 ? UserSexEnum.USER_MAN.getCode() : UserSexEnum.USER_WOMAN.getCode());

            baseResp.buildDefaultSuccessResp(detectFaceReq);
        } catch (Exception e) {
            ExceptionUtils.buildExceptionResp("AiServiceImpl", null, baseResp, e.getMessage(), e);
        }
        log.info("detectFace.resp:{}", baseResp.toString());
        return baseResp;
    }
}
